
package com.fqgj.sentry.security;

import com.fqgj.sentry.common.cache.RequestLocalInfo;
import com.fqgj.sentry.common.exception.BizException;
import com.fqgj.sentry.common.exception.enums.ErrorCodeEnums;
import com.fqgj.sentry.manage.entity.*;
import com.fqgj.sentry.manage.enums.UserLevelEnums;
import com.fqgj.sentry.manage.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by lpp kangping.ying@yuntu-inc.com
 *
 * @description
 * @create 2017-07-11 上午11:05
 */

@Component
public class CustomPermissionEvaluator implements PermissionEvaluator {
    @Autowired
    private UserService userService;
    @Autowired
    private GroupManagerService groupManagerService;
    @Autowired
    private ApplicationService applicationService;
    @Autowired
    private RolePermissionService rolePermissionService;
    @Autowired
    private PermissionService permissionService;

    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        return hasPermission(authentication, permission);
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable serializable, String targetType, Object permission) {
        return true;
    }

    /**
     * 简单的字符串比较，相同则认为有权限
     */
    private boolean hasPermission(Authentication authentication, Object permission) {
        String appCode = RequestLocalInfo.getCurrentAppCode();
        Long merchantId = RequestLocalInfo.getCurrentMerchantId();
        Long userId = RequestLocalInfo.getCurrentUserId();
        if (userId == null) {
            throw new BizException(ErrorCodeEnums.no_access_right, "需要登陆才能访问");
        }
        //判断用户是否为  管理员权限
        McUserEntity mcUserEntity = userService.selectById(userId);
        if (mcUserEntity.getLevel() == UserLevelEnums.merchant_admin.getLevel()) {
            return true;
        }
        if (StringUtils.isBlank(appCode)) {
            throw new BizException(ErrorCodeEnums.app_not_exist_error, "请选择应用");
        }
        McApplicationEntity applicationEntity = applicationService.selectByMerchantIdAndAppCode(merchantId, appCode);
        if (applicationEntity == null) {
            throw new BizException(ErrorCodeEnums.app_not_choose_error);
        }
        //查询权限组
        McGroupManagerEntity groupManagerEntity = groupManagerService.selectByUserIdAndAppId(userId, applicationEntity.getId());
        if (groupManagerEntity == null) {
            throw new BizException(ErrorCodeEnums.permission_error, "请联系管理员,分配权限");
        }
        String roleIds = groupManagerEntity.getRolesId();
        String[] roleIdList = roleIds.split(",");
        if (roleIdList.length == 0) {
            throw new BizException(ErrorCodeEnums.permission_error, "请联系管理员,分配权限");
        }
        List<String> permissionList = new ArrayList<>();
        for (String roleId : roleIdList) {
            List<McRolePermissionEntity> rolePermissionEntityList = rolePermissionService.findListByRoleId(Long.valueOf(roleId));
            for (McRolePermissionEntity rolePermissionEntity : rolePermissionEntityList) {
                McPermissionEntity mcPermissionEntity = permissionService.selectOneById(rolePermissionEntity.getPermissionId());
                if (mcPermissionEntity == null) {
                    throw new BizException(ErrorCodeEnums.permission_error, "请联系管理员,分配权限");
                }
                permissionList.add(mcPermissionEntity.getPermission());
            }
        }
        String currentPermission = permission.toString();
        if(permissionList.contains(currentPermission)){
            return true;
        }
        throw new BizException(ErrorCodeEnums.permission_error, "请联系管理员,分配权限");
    }
}
